<template>
  <el-drawer title="项目配置" v-model="data.drawer" :show-close="true">
    <div class="draw-content">
      <!-- <el-divider>主题</el-divider>
      <div class="flex-justify-center day-mode">
        <el-switch
          v-model="data.nightMode"
          active-text="夜间模式"
          inactive-text="日间模式"
          @change="changeSetting('nightMode', data.nightMode)"
        ></el-switch>
      </div> -->
      <!-- <el-divider>导航栏模式</el-divider>
      <div class="nav-row">
        <el-tooltip
          effect="dark"
          placement="bottom"
          v-for="(item, index) in data.navbarList"
          :key="index"
          :content="item"
          :disabled="!data.drawer"
        >
          <div
            :class="[
              'nav-item',
              `nav-item-${index.toString()}`,
              { active: data.navbarType + '' === item + '' },
            ]"
            @click="changeSetting('navbarType', item)"
          ></div>
        </el-tooltip>
      </div> -->
      <el-divider>系统主题</el-divider>
      <div class="checkbox-row">
        <div
          class="checkbox-item"
          v-for="(item, index) in data.systemThemeList"
          :key="index"
          :class="{ active: item + '' === data.systemThemeColor + '' }"
          :style="{ backgroundColor: item + '' }"
          @click="changeSetting('systemThemeColor', item)"
        ></div>
        <el-color-picker
          v-model="data.systemThemeColor"
          @active-change="changeSetting('systemThemeColor', $event)"
        ></el-color-picker>
      </div>
      <el-divider>顶栏主题</el-divider>
      <div class="checkbox-row">
        <div
          class="checkbox-item"
          v-for="(item, index) in data.navbarThemeList"
          :key="index"
          :class="{ active: item + '' === data.navbarThemeColor + '' }"
          :style="{ backgroundColor: item + '' }"
          @click="changeSetting('navbarThemeColor', item)"
        ></div>
        <el-color-picker
          v-model="data.navbarThemeColor"
          @active-change="changeSetting('navbarThemeColor', $event)"
        ></el-color-picker>
      </div>
      <el-divider>菜单主题</el-divider>
      <div class="checkbox-row">
        <div
          class="checkbox-item"
          v-for="(item, index) in data.sidebarThemeList"
          :key="index"
          :class="{ active: item + '' === data.sidebarThemeColor + '' }"
          :style="{ backgroundColor: item + '' }"
          @click="changeSetting('sidebarThemeColor', item)"
        ></div>
        <el-color-picker
          v-model="data.sidebarThemeColor"
          @active-change="changeSetting('sidebarThemeColor', $event)"
        ></el-color-picker>
      </div>
      <!-- <el-divider>界面显示</el-divider>
      <div class="other-row">
        <span>面包屑</span>
        <el-switch
          v-model="data.showBreadcrumb"
          class="custom-switch"
          @change="changeSetting('showBreadcrumb', $event)"
        ></el-switch>
      </div>
      <div class="other-row">
        <span>导航页</span>
        <el-switch
          v-model="data.showTabs"
          class="custom-switch"
          @change="changeSetting('showTabs', $event)"
        ></el-switch>
      </div> -->
    </div>
    <el-button class="draw-save" @click="saveTheme">保存</el-button>
  </el-drawer>
</template>

<script lang="ts" setup>
import { configEdit, queryListBychannelTag } from "@/api/config";
import { ElMessage } from "element-plus";
import { reactive, toRefs, onMounted, watch, ref } from "vue";
import { useStore } from "vuex";
import { setThemes, getThemes, themeIsExist } from "./../utils/storage";
const store = useStore();

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
});
const emit = defineEmits(["update:modelValue"]);

onMounted(() => {
  initData();
});

const configList = ref<any[]>([]);
const systemThemeColor = ref<string>("");
const navbarThemeColor = ref<string>("");
const sidebarThemeColor = ref<string>("");

const initData = async () => {
  let res = await queryListBychannelTag({ channel_tag: "后台背景" });
  console.log("后台背景", res);
  if (res) {
    configList.value = res.data;
    res.data.forEach((config: any) => {
      if (config.params_key == "systemThemeColor") {
        systemThemeColor.value = config.params_value;
        changeSetting("systemThemeColor", config.params_value);
      } else if (config.params_key == "navbarThemeColor") {
        navbarThemeColor.value = config.params_value;
        changeSetting("navbarThemeColor", config.params_value);
      } else if (config.params_key == "sidebarThemeColor") {
        sidebarThemeColor.value = config.params_value;
        changeSetting("sidebarThemeColor", config.params_value);
      }
    });
  }
  // if (!themeIsExist()) {
  //   changeSetting("systemThemeColor", data.systemThemeColor);
  //   changeSetting("navbarThemeColor", data.navbarThemeColor);
  //   changeSetting("sidebarThemeColor", data.sidebarThemeColor);
  // }
  _getThemes({ data });
};

const saveTheme = () => {
  configList.value.forEach((config) => {
    if (
      (config.params_key == "systemThemeColor" &&
        config.params_value != systemThemeColor.value) ||
      (config.params_key == "navbarThemeColor" &&
        config.params_value != navbarThemeColor.value) ||
      (config.params_key == "sidebarThemeColor" &&
        config.params_value != sidebarThemeColor.value)
    ) {
      configEdit({ ...config });
    }
  });
  ElMessage({ message: "保存成功", type: "success" });
};

const changeSetting = async (type: any, value: any) => {
  let configs = configList.value.filter((config) => config.params_key == type);
  if (configs && configs.length > 0) {
    let config = configs[0];
    config.params_value = value;
  }
  _changeSetting({ type, value, store, data });
};

// 定义变量
const data = reactive({
  drawer: false,
  nightMode: false,
  navbarType: "左侧菜单模式",
  navbarList: [
    "左侧菜单模式",
    "顶部菜单混合模式",
    "顶部菜单模式",
    "左侧菜单混合模式",
  ],
  systemThemeColor: "#536DF3",
  systemThemeList: [
    "#0960BD",
    "#0084F4",
    "#009688",
    "#536DF3",
    "#FF5C93",
    "#EE4F12",
    "#0096C7",
    "#9C27B0",
    "#FF9800",
  ],
  navbarThemeColor: "#5172DC",
  navbarThemeList: [
    "#FFFFFF",
    "#151515",
    "#009688",
    "#5172DC",
    "#409EFF",
    "#E74C3C",
    "#24292E",
    "#394664",
    "#001529",
    "#383F45",
  ],
  sidebarThemeColor: "#FFFFFF",
  sidebarThemeList: [
    "#001529",
    "#212121",
    "#273352",
    "#FFFFFF",
    "#191B24",
    "#191A23",
    "#304156",
    "#28333E",
    "#344058",
    "#383F45",
  ],
  showBreadcrumb: true,
  showTabs: true,
});

// 主题切换
const _changeSetting = (params: any) => {
  let { type, value, store, data } = params;
  data[type] = value;
  settingThemes({ type, value });
  if (type === "navbarType") {
    data.drawer = false;
    store.commit("getNavbarType", value);
  }
};

// 设置主题并暂存缓存
const settingThemes = (params: any) => {
  const { type, value } = params;
  let themes = getThemes();
  themes[type] = value;
  setThemes(themes);
  _getThemes(null);
};

// 读取主题
const _getThemes = (params: any) => {
  let themes = getThemes();
  if (params) {
    let { data } = params;
    Object.keys(data).forEach((key) => {
      data[key] = themes[key] || data[key];
    });
  }
  let attribute = "";
  if (themes.systemThemeColor) {
    attribute += `--systemThemeColor: ${themes.systemThemeColor};`;
    let result = lighten(themes.systemThemeColor, 58);
    attribute += `--systemThemeColorActive: ${result};`;
  }
  if (themes.navbarThemeColor) {
    attribute += `--navbarThemeColor: ${themes.navbarThemeColor};`;
    let result = lighten(themes.navbarThemeColor, 6);
    attribute += `--sidebarThemeColorActive: ${result};`;
  }
  if (themes.sidebarThemeColor) {
    attribute += `--sidebarThemeColor: ${themes.sidebarThemeColor};`;
    toggleClass({
      flag: themes.sidebarThemeColor === "#FFFFFF",
      cls: "sidebar--white",
    });
  }
  toggleClass({
    flag: themes.nightMode,
    cls: "night-mode",
  });
  toggleClass({
    flag: themes.showBreadcrumb,
    dom: ".el-breadcrumb",
    cls: "is-show",
  });
  toggleClass({
    flag: themes.showTabs,
    dom: ".tabs-content",
    cls: "is-show",
  });
  toggleClass({
    flag: themes?.navbarThemeColor
      ? themes.navbarThemeColor === "#FFFFFF"
      : true,
    cls: "navbar--white",
  });
  data.navbarList.forEach((item, index) => {
    toggleClass({
      flag: item === data.navbarType,
      cls: `layout-type-${index + 1}`,
    });
  });

  document.querySelector(":root")?.setAttribute("style", attribute);
};

// 添加移除class
const toggleClass = (params: any) => {
  let { flag, cls, dom } = params;
  dom = dom || "body";
  let classList = document.querySelector(dom)?.classList;
  flag ? classList?.add(cls) : classList?.remove(cls);
};

// 颜色计算方法
const lighten = (color: any, amount: any) => {
  color = color.indexOf("#") >= 0 ? color.substring(1, color.length) : color;
  amount = Math.trunc((255 * amount) / 100);
  return `#${addLight(color.substring(0, 2), amount)}${addLight(
    color.substring(2, 4),
    amount
  )}${addLight(color.substring(4, 6), amount)}`;
};

// 颜色计算方法
const addLight = (color: any, amount: any) => {
  const cc = parseInt(color, 16) + amount;
  const c = cc > 255 ? 255 : cc;
  return c.toString(16).length > 1 ? c.toString(16) : `0${c.toString(16)}`;
};

watch(props, (newVal) => (data.drawer = newVal.modelValue));
watch(data, (newVal) => emit("update:modelValue", newVal.drawer));
</script>

<style lang="scss" scoped>
@import "@/assets/css/themes.scss";
$nav-bg-dark: #273352;

.draw-content {
  height: calc(100% - 30px);
  overflow-y: auto;
}

.day-mode {
  padding-bottom: 10px 0;
}

.nav-row {
  display: flex;
}

.nav-item {
  width: 56px;
  height: 50px;
  margin-right: 16px;
  border-radius: 4px;
  background-color: #f0f2f5;
  position: relative;
  box-shadow: 0 0 2px rgba(20, 16, 16, 0.2);
  cursor: pointer;
  border: 2px solid #fff;

  &.active {
    border-color: $systemTheme;
  }

  //  box-shadow: 0 0 2.5px red;
  &.nav-item::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    width: 17px;
    background-color: $nav-bg-dark;
    border-top-left-radius: inherit;
    border-bottom-left-radius: inherit;
  }

  &.nav-item::after {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 12px;
    background-color: #fff;
    border-top-left-radius: inherit;
    border-top-right-radius: inherit;
  }

  &.nav-item-0::before {
    z-index: 1;
  }

  &.nav-item-1::before {
    background-color: #fff;
  }

  &.nav-item-1::after,
  &.nav-item-2::after {
    background-color: $nav-bg-dark;
    border-top-left-radius: inherit;
    border-bottom-right-radius: 0;
  }

  &.nav-item-2::before {
    display: none;
  }

  &.nav-item-3::before {
    z-index: 1;
    width: 14px;
    box-shadow: 8px 0 0 #fff;
  }

  &.nav-item-3::after {
    right: 0;
    border-bottom-right-radius: 0;
  }
}

.checkbox-row {
  display: flex;
  justify-content: space-between;

  .checkbox-item {
    width: 20px;
    height: 20px;
    border: 1px solid #ddd;
    border-radius: 2px;
    cursor: pointer;
    position: relative;

    &.active {
      border-color: $systemTheme;

      &::before {
        content: "\2713";
        font-size: 14px;
        color: #fff;
        position: absolute;
        top: -1px;
        left: 3px;
      }
    }
  }
}

::v-deep(.el-color-picker) {
  width: 20px !important;
  height: 20px !important;
}

::v-deep(.el-color-picker__trigger) {
  width: 20px !important;
  height: 20px !important;
}

::v-deep(.el-color-picker__color) {
  border: none !important;
}

::v-deep(.el-color-picker__trigger) {
  padding: 0 !important;
}
.other-row {
  font-size: 14px;
  display: flex;
  justify-content: space-between;
  align-content: center;
  color: #273352;
  margin-bottom: 15px;
}
.night-mode {
  .other-row {
    color: #c9d1d9;
  }
}

.draw-save {
  height: 32px;
  width: 100%;
  background-color: $systemTheme;
  color: #fff;
}
</style>
